#coding: utf-8
from django.http import HttpResponse
import json
import Queue
import datetime
import threading
import time
import os
import platform
from .models import RepositoryMenu,RepositoryInfo
from django.forms.models import model_to_dict
def getmenu(request):
    list_count = RepositoryMenu.objects.count()
    list1 = []
    for obj in RepositoryMenu.objects.all():
        pid = obj.pid
        text = obj.text
        remark = obj.remark
        state = obj.state
        iconCls = obj.iconCls
        url = obj.url
        dict1 = {'id':obj.pk,'pid' : pid,'text': text,'remark': remark,'state': state,'iconCls': iconCls,'url':url}
        list1.append(dict1)
    result = {"total": list_count, 'rows': list1}
    return HttpResponse(json.dumps(result))
# Create your views here.
def addMenu(request):
    ret = {'state': 200, 'message': "添加成功"}
    data = json.loads(request.body)
    print data
    RepositoryMenu.objects.create(**data)
    return HttpResponse(json.dumps(ret), content_type="application/json")
def  modifyMenu(request):
    ret = {'state': 200, 'message': "修改成功"}
    data = json.loads(request.body)
    print data
    number = data.pop('id')
    RepositoryMenu.objects.filter(id=number).update(**data)
    return HttpResponse(json.dumps(ret), content_type="application/json")


def repositoryList(request):
    get_id = request.POST.get('id',None)

    if not get_id:
        get_id = 0
        ret = {'state': 200, 'message': "添加成功"}
        data1 = RepositoryMenu.objects.filter(pid=get_id)

        data = [model_to_dict(i) for i in data1]
        print data

        return HttpResponse(json.dumps(data), content_type="application/json")

    else:
        ret = {'state': 200, 'message': "添加成功"}
        data1 = RepositoryMenu.objects.filter(pid=get_id)

        data = [model_to_dict(i) for i in data1]
        print data

        return HttpResponse(json.dumps(data), content_type="application/json")
def getRepositoryList(request):
    get_id = request.GET.get('id', None)
    print get_id
    list1 = []
    data1 = RepositoryInfo.objects.filter(repositorymenu_id=get_id)
    count = data1.count()
    for obj in data1:
        repositorymenu_id = obj.repositorymenu_id
        title = obj.title
        content = obj.content
        id = obj.id
        create_time1 = obj.create_time
        create_time = create_time1.strftime('%Y-%m-%d %H:%M:%S')
        operator = obj.operator

        dict1 = { 'title': title,'content': content,'create_time': create_time,'operator': operator,'id': id}
        list1.append(dict1)
    result = {"total": count, 'rows': list1}
    print result
    return HttpResponse(json.dumps(result), content_type="application/json")





dictQueue={}
lock_list2 = threading.Lock()
def getRepositoryData(req):
    data = json.loads(req.body)
    dictQueue[data['uuid']] = Queue.Queue(0)
    r1=None
    global r1
    def w():
        global r1
        while True:
            q = dictQueue[data['uuid']]
            if q.empty():
                time.sleep(1)
            else:
                lock_list2.acquire()
                getQ = q.get()
                getUUID = getQ['uuid']
                getid = getQ['id']
                obj = RepositoryInfo.objects.filter(id=getid)
                objdata = [model_to_dict(i) for i in obj]
                lock_list2.release()

                r1 = objdata[0]
                print r1
                break

    t= threading.Thread(target=w)
    t.start()
    t.join()
    print type(r1)
    print r1,"67676768"
    return HttpResponse(json.dumps(r1), content_type="application/json")


def putRepositoryData(req):
     try:
        data = json.loads(req.body)
        getUuid = data['uuid']
        q = dictQueue[getUuid]
        q.put(data)
     except Exception, e:
         print e

     return HttpResponse(json.dumps(data),content_type="application/json")


def addRepositoryData(req):
    ret = {'state': 200, 'message': "添加成功"}
    data = json.loads(req.body)
    print data
    repositorymenu_id = data.pop('repositorymenu_id')
    print repositorymenu_id
    obj = RepositoryMenu.objects.get(id = repositorymenu_id)
    print obj
    data['repositorymenu_id'] = obj
    print data

    try:
        RepositoryInfo.objects.create(**data)
    except Exception, e:
        print e
        ret = {'state': 400, 'message': "标题重复"}
        print ret
        print type(ret)
        return HttpResponse(json.dumps(ret), content_type="application/json")

    return HttpResponse(json.dumps(ret), content_type="application/json")
def getTitle(request):
    list1 = []
    aa = request.GET
    repositorymenu_id= request.GET['repositorymenu_id']
    print    repositorymenu_id

    obj = RepositoryMenu.objects.get(id = repositorymenu_id)
    objdata =  RepositoryInfo.objects.filter(repositorymenu_id = obj)
    for i in objdata:
        id = i.pk
        title = i.title
        content = i.content
        dict1 = { 'id': id,'title': title,'content': content}
        list1.append(dict1)
    return HttpResponse(json.dumps(list1), content_type="application/json")

def getContent(request):
    print request.GET
    id = request.GET['id']
    print id
    obj = RepositoryInfo.objects.get(id=id)
    content = obj.content
    response= HttpResponse()

    #response['X-Frame-Options'] = "ALLOW-FROM http://yw.dgg.net"
    response.write(content)

    return response


def updateRepositoryData(request):
    ret = {'state': 200, 'message': "修改成功"}
    data = json.loads(request.body)
    print data
    id = data.pop('id')
    RepositoryInfo.objects.filter(id=id).update(**data)
    return HttpResponse(json.dumps(ret), content_type="application/json")

def datetime_image_name():
    d1 = datetime.datetime.today()
    d1 = "%s%s%s%s%s%s%s" % (d1.year, d1.month, d1.day, d1.hour, d1.minute,
                              d1.second, d1.microsecond)

    return d1 + ".png"

def uploader(request):
    image = request.FILES.get("upload")
    image_name = datetime_image_name()
    white_image = get_static_lujing(image_name)

    with  open(white_image, "wb") as f:
        f.write(image.read())

    tupian = """{"uploaded": 1,"fileName": "%s","url": "/static/images/%s"} """ % (image_name, image_name)

    return HttpResponse(tupian)
def get_static_lujing(image_name=None):
    #static = os.path.dirname(os.path.abspath(__file__))
    sysstr = platform.system()
    if (sysstr == "Windows"):
        static = "G:/site2/static/images"
    else:
        static = "/usr/local/nginx/html/static/images"


    static = static + os.sep

    if image_name:
        return static + os.sep + image_name
    else:
        return static





